#include "livres.h"
#include "ui_livres.h"
#include <QtSql>
#include <QTableView>
#include <QSqlQuery>
#include <QDataWidgetMapper>

Livres::Livres(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Livres)
{
    ui->setupUi(this);

    model = new QSqlTableModel(ui->tableView);
    model->setTable("livre");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();

    model->setHeaderData(0, Qt::Horizontal, tr("ID"));
    model->setHeaderData(1, Qt::Horizontal, tr("TITRE"));
    model->setHeaderData(2, Qt::Horizontal, tr("AUTEUR"));
    model->setHeaderData(3, Qt::Horizontal, tr("GENRE"));

    ui->tableView->setModel(model);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->hideColumn(0);
    //ui->tableView->resizeColumnsToContents();

    QDataWidgetMapper *mapper = new QDataWidgetMapper(this);
    mapper->setModel(model);
    mapper->addMapping(ui->titleEdit, model->fieldIndex("titre"));
    mapper->addMapping(ui->AuthorEdit, model->fieldIndex("auteur"));
    mapper->addMapping(ui->genreEdit, model->fieldIndex("genre"));

    connect(ui->tableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            mapper, SLOT(setCurrentModelIndex(QModelIndex)));

}

Livres::~Livres()
{
    delete ui;
}

void Livres::on_submit_clicked()
{
    model->database().transaction();
    if (model->submitAll())
        model->database().commit();
}
